package cn.jksoft.businessclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingApi;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseSwipeBackCompatActivity;
import cn.jksoft.businessclient.bean.CustCardEntity;
import cn.jksoft.businessclient.ui.adapter.MembershipCardAdapter;
import cn.jksoft.businessclient.ui.views.RecycleViewDivider;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Author:  nick
 * Email:   nickdevp@gmail.com
 * Date:    16/5/5 09:37.
 * Description: 会员卡页
 */
public class MembershipCardActivity extends BaseSwipeBackCompatActivity implements SwipeRefreshLayout.OnRefreshListener {


    @Bind(R.id.recyclerview_card_list)
    RecyclerView mRecyclerviewCard;
    @Bind(R.id.swipe_container)
    SwipeRefreshLayout mSwipeLayout;

    private TextView cardNum;
    private LinearLayoutManager linearLayoutManager;
    private MembershipCardAdapter adapter;
    private List<CustCardEntity.CustomerCardListEntity> dataBeanList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_membership_card);
        ButterKnife.bind(this);
        initTitle("会员卡");
        initBackClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initView();
    }

    private void initView() {
        linearLayoutManager = new LinearLayoutManager(this);
        mSwipeLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mRecyclerviewCard.setLayoutManager(linearLayoutManager);
        mRecyclerviewCard.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL));
        dataBeanList = new ArrayList<CustCardEntity.CustomerCardListEntity>();
        adapter = new MembershipCardAdapter(this, dataBeanList);
        adapter.setItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                CustCardEntity.CustomerCardListEntity itemBean = dataBeanList.get((int) v.getTag());
                intent.putExtra("memberId", itemBean.getMEMBER_ID());
                intent.putExtra("memberName", itemBean.getCARD_NAME());
                if (itemBean.getCARD_KIND() == 1) {
                    //储值卡
                    intent.putExtra("balance", itemBean.getBALANCE() / 100);
                } else {
                    //次卡
                    Bundle data = new Bundle();
                    data.putSerializable("entity", itemBean);
                    intent.putExtras(data);

                }
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        mRecyclerviewCard.setAdapter(adapter);
        setHeader(mRecyclerviewCard);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(R.color.colorPrimary, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, R.color.colorPrimary);
        mSwipeLayout.setDistanceToTriggerSync(400);
        mSwipeLayout.setColorSchemeColors(R.color.white);
        mSwipeLayout.setRefreshing(true);

        initData();
    }

    private void setHeader(RecyclerView view) {
        View header = LayoutInflater.from(this).inflate(R.layout.header_membership_card, view, false);
        cardNum = (TextView) header.findViewById(R.id.tv_card_num);
        adapter.setHeaderView(header);
    }


    private void initData() {
        mSwipeLayout.setVisibility(View.VISIBLE);

        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());
            json.put("customerId", getIntent().getLongExtra("customerId", -1));
            json.put("custCmId", getIntent().getLongExtra("custCmId", -1));
            json.put("prodSkuIds", getIntent().getStringExtra("prodSkuIds"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.qryCustomerCardList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CustCardEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(CustCardEntity custCardEntity) {

                        if ("1".equals(custCardEntity.getIs_successful())) {
                            if (custCardEntity.getCustomerCardList() != null) {
                                dataBeanList.addAll(custCardEntity.getCustomerCardList());
                                adapter.notifyDataSetChanged();
                            }
                        }
                        cardNum.setText("可使用会员卡" + custCardEntity.getCardTotalNumber() + "张");
                        if (dataBeanList == null || dataBeanList.size() == 0) {
                            mSwipeLayout.setVisibility(View.GONE);
                        }
                        mSwipeLayout.setRefreshing(false);
                    }
                });

    }

    @Override
    public void onRefresh() {
        dataBeanList.clear();
        initData();
    }
}
